<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AdminOperationLog extends Model
{
    use HasFactory;

    protected $fillable = [
        'admin_user_id',
        'action',
        'module',
        'target_type',
        'target_id',
        'description',
        'request_data',
        'response_data',
        'ip_address',
        'user_agent',
        'result'
    ];

    protected $casts = [
        'request_data' => 'array',
        'response_data' => 'array'
    ];

    // 关联A端用户
    public function adminUser()
    {
        return $this->belongsTo(AdminUser::class);
    }

    // 操作结果常量
    const RESULT_SUCCESS = 'success';       // 成功
    const RESULT_FAILED = 'failed';         // 失败
    const RESULT_ERROR = 'error';           // 错误

    // 获取操作结果显示名称
    public function getResultDisplayAttribute()
    {
        $results = [
            self::RESULT_SUCCESS => '成功',
            self::RESULT_FAILED => '失败',
            self::RESULT_ERROR => '错误'
        ];

        return $results[$this->result] ?? $this->result;
    }

    // 记录操作日志
    public static function log($adminUserId, $action, $module, $targetType = null, $targetId = null, $description = null, $requestData = null, $responseData = null, $result = self::RESULT_SUCCESS)
    {
        return self::create([
            'admin_user_id' => $adminUserId,
            'action' => $action,
            'module' => $module,
            'target_type' => $targetType,
            'target_id' => $targetId,
            'description' => $description,
            'request_data' => $requestData,
            'response_data' => $responseData,
            'ip_address' => request()->ip(),
            'user_agent' => request()->userAgent(),
            'result' => $result
        ]);
    }
}